package com.uphone.kingmall.activity.order;

import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.LogUtils;
import com.china.zhuoyue.R;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.uphone.kingmall.adapter.OrderGoodListAdapter;
import com.uphone.kingmall.app.MyApplication;
import com.uphone.kingmall.base.BaseActivity;
import com.uphone.kingmall.bean.OrderDetailBean;
import com.uphone.kingmall.bean.PayAliCallbackBean;
import com.uphone.kingmall.bean.PayResult;
import com.uphone.kingmall.bean.PayWxCallbackBean;
import com.uphone.kingmall.listener.onNormalRequestListener;
import com.uphone.kingmall.main.MainActivity;
import com.uphone.kingmall.utils.ActivityCollector;
import com.uphone.kingmall.utils.AppUtil;
import com.uphone.kingmall.utils.CommonUtil;
import com.uphone.kingmall.utils.DialogUtil;
import com.uphone.kingmall.utils.GsonUtils;
import com.uphone.kingmall.utils.MyUrl;
import com.uphone.kingmall.utils.OkGoUtils;
import com.uphone.kingmall.utils.intent.IntentData;
import com.uphone.kingmall.view.dialog.RadishDialog;
import com.uphone.kingmall.wxapi.WXPayEntryActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * <pre>
 *     author : radish
 *     e-mail : 15703379121@163.com
 *     time   : 2019/3/20
 *     desc   :
 * </pre>
 */
public class OrderPayActivity extends BaseActivity {

    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.rl_address)
    RelativeLayout rlAddress;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.tv_postFee)
    TextView tvPostFee;
    @BindView(R.id.et_remark)
    EditText etRemark;
    @BindView(R.id.rb_ali)
    RadioButton rbAli;
    @BindView(R.id.rb_wchat)
    RadioButton rbWchat;
    @BindView(R.id.rb_union)
    RadioButton rbUnion;
    @BindView(R.id.rb_wallet)
    RadioButton rbWallet;
    @BindView(R.id.rg_pay)
    RadioGroup rgPay;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.rv_good)
    RecyclerView rvGood;
    private int addId = -1;
    private double totalMoney;
    @IntentData
    private OrderDetailBean.OrderBean bean;
    private HttpParams params;
    private RadishDialog dialog;

    @Override
    public int getLayoutContentId() {
        return R.layout.kingmall_activity_order_pay;
    }

    @Override
    public void initView() {
        CommonUtil.initTitle(this, "订单支付", ll);
        rgPay.check(R.id.rb_ali);
    }

    @Override
    public void initData() {
        if (bean != null) {
            if (!TextUtils.isEmpty(bean.getReceiverName())) {
                rlAddress.setVisibility(View.VISIBLE);
                tvName.setText("收货人：" + bean.getReceiverName());
                tvAddress.setText("" + bean.getReceiverName());
                tvPhone.setText("" + bean.getReceiverTel());
            }else {
                rlAddress.setVisibility(View.GONE);
            }

            tvShopName.setText("" + bean.getShopName());
            if (bean.getPostType() == 1) {
                //快递
                tvPostFee.setText("快递：" + bean.getPostFee());
            } else {
                tvPostFee.setText("到店");
            }
            tvMoney.setText("" + bean.getOrderFee());

            rvGood.setLayoutManager(new LinearLayoutManager(this));
            OrderGoodListAdapter adapter = new OrderGoodListAdapter();
            rvGood.setAdapter(adapter);
            adapter.setNewData(bean.getGoodslist());
        }


    }

    @OnClick({R.id.tv_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_submit:
                submitOrder();
                break;
        }
    }

    private void submitOrder() {
        if (bean != null) {
            params = new HttpParams();
            params.put("payType", rgPay.getCheckedRadioButtonId() == R.id.rb_ali ? 1 : (rgPay.getCheckedRadioButtonId() == R.id.rb_wchat ? 2 : 3));
            if (rgPay.getCheckedRadioButtonId() == R.id.rb_wallet) {
                //钱包支付

                dialog = DialogUtil.showDialogWalletPay(OrderPayActivity.this, new DialogUtil.OnWalletPayDialogCallBack() {
                    @Override
                    public void callBack(RadishDialog dialog, View view, String psd) {

                        params.put("paypass", psd);

                        submitOrder2();
                    }
                });
//                IntentUtils.getInstance()
//                        .with(this, WalletPayPassActivity.class)
//                        .putString(ConstansUtils.PARA, WalletPayPassActivity.Pay)
//                        .putString("clazz", getClass().getName())
//                        .start();
            } else {
                submitOrder2();
            }

        }

    }

    private void submitOrder2() {
        params.put("orderId", bean.getOrderId());
        OkGoUtils.progressRequest(MyUrl.orderpay, this, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                if (code == 1) {
                    //0元支付
                    paySuccess();
                    return;
                }
                if (code != 0) {
                    return;
                }
                try {
                    JSONObject jsonObject = new JSONObject(body);
                    String sign = jsonObject.getString("sign");
                    if (TextUtils.isEmpty(sign)) {
                        paySuccess();
                    } else {
                        if (rgPay.getCheckedRadioButtonId() == R.id.rb_ali) {
                            //支付宝支付
                            alipay(body);
                        } else if (rgPay.getCheckedRadioButtonId() == R.id.rb_wchat) {
                            // 微信支付
                            wxPay(body);
                        } else {
                            // 佣金支付
                            paySuccess();
                        }
                    }
                } catch (JSONException e) {
                    LogUtils.e("异常：" + e.toString());
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    private void wxPay(final String body) {
        AppUtil.checkWchat(this, new AppUtil.AppCheckCallback() {
            @Override
            public void callBack() {
                PayWxCallbackBean bean = GsonUtils.getGson().fromJson(body, PayWxCallbackBean.class);
                PayWxCallbackBean.SignBean sign = bean.getSign();
                PayReq request = new PayReq();
                request.appId = sign.getAppId();
                request.partnerId = sign.getPartnerId();
                request.prepayId = sign.getPrepayId();
                request.packageValue = sign.getPackageValue();
                request.nonceStr = sign.getNonceStr();
                request.timeStamp = sign.getTimeStamp();
                request.sign = sign.getSign();
                WXPayEntryActivity.activity = OrderPayActivity.this;
                MyApplication.api.sendReq(request);
            }
        });

    }

    @Override
    public void wxPaySuccess() {
        super.wxPaySuccess();
        paySuccess();
    }

    private void paySuccess() {
        if (dialog != null && dialog.isShowing()){
            dialog.dismiss();
        }
        ActivityCollector.removeAll(MainActivity.class);
        CommonUtil.startIntentType(OrderPayActivity.this, AllOrderActivity.class, 2);
    }

    private void alipay(final String body) {
        AppUtil.checkAli(this, new AppUtil.AppCheckCallback() {
            @Override
            public void callBack() {
                PayAliCallbackBean bean = GsonUtils.getGson().fromJson(body, PayAliCallbackBean.class);
                final String sign = bean.getSign();
                // 必须异步调用
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(OrderPayActivity.this);
                        final Map<String, String> resultMap = alipay.payV2(sign, true);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                PayResult result = new PayResult(resultMap);
                                String resultStatus = result.getResultStatus();
                                if (TextUtils.equals(resultStatus, "9000")) {
                                    LogUtils.e("handleMessage: 已经支付成功，支付成功");
                                    com.blankj.utilcode.util.ToastUtils.showShort("支付成功");
                                    paySuccess();
                                } else if (TextUtils.equals(resultStatus, "6001")) {
                                    LogUtils.e("handleMessage: 已经取消支付");
                                    com.blankj.utilcode.util.ToastUtils.showShort("支付取消");
                                } else {
                                    LogUtils.e("handleMessage: 未知状态");
                                    com.blankj.utilcode.util.ToastUtils.showShort(resultStatus);
                                }
                            }
                        });
                    }
                }).start();
            }
        });

    }

    @Override
    public void onPayPsdSuccess(String passWord) {
        super.onPayPsdSuccess(passWord);
        params.put("paypass", passWord);

        submitOrder2();
    }
}
